import store from '@/store'
import { get, post } from '@/utils/request'

const cacheData = {}

const prefixUrl = '/api/adminPortal'
const tailUrl = 'getListByCon'

// 不进行分页
const NOT_PAGER = { is_paginate: 0 }

const mapDataCallBack = (res, keyName = 'name') => {
  return res.data.map((item) => ({ id: item.id, name: item[keyName] }))
}

/**
 * 缓存数据
 * @param {string} api 接口地址
 * @param {string} params 参数地址 用于区分缓存 ‘’
 * @param {string} key name标记
 */
const cacheAction = (api, params = {}, key = 'name') => {
  const cacheParams = JSON.stringify(params)
  return new Promise((resolve) => {
    if (cacheData[`${api}${cacheParams}`]) {
      resolve(cacheData[`${api}${cacheParams}`])
      return
    }
    get(api, { ...NOT_PAGER, ...params })
      .then((res) => mapDataCallBack(res, key)).then((data) => {
        cacheData[`${api}${cacheParams}`] = data
        resolve(cacheData[`${api}${cacheParams}`])
      })
  })
}

// 清空缓存
export const emptyCacheAction = () => {
  Object.keys(cacheData).forEach((key) => delete cacheData[key])
}
